package com.css.upms.biz.security.autherization;

import com.css.common.security.support.CssUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * PermissionService
 *
 * @author hanyx
 * @date 2019/05/04
 */
@Slf4j
@Component("pms")
public class PermissionService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 告诉 spring security 能不能访问
     *
     * @param request
     * @param authentication
     * @return
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;

        if (principal instanceof CssUser) {
            CssUser cssUser = ((CssUser) principal);
            //如果用户名是admin，就永远返回true
            if ("admin".equals(cssUser.getUsername())) {
                hasPermission = true;
            } else {
                // 读取用户所拥有权限的所有URL
                Collection<GrantedAuthority> grantedAuthorities = cssUser.getAuthorities();
                for (GrantedAuthority authority : grantedAuthorities) {
                    // 只要有匹配的就退出循环,表示可以访问
                    if (antPathMatcher.match(authority.getAuthority(), request.getRequestURI())) {
                        hasPermission = true;
                        break;
                    }
                }
            }
        }
        return hasPermission;
    }



    /**
     * 判断接口是否有xxx:xxx权限
     *
     * @param permission 权限
     * @return {boolean}
     */
    public boolean hasPermission(String permission) {
        if (StringUtils.hasText(permission)) {
            return false;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
    }
}
